import pool from '../database/index.js'
import { SplicingImagePaths } from '../utils/tools.js'

/**查询用户列表 */
export const getUserList = async(req,res)=>{
      const { userId  } = req
      const { page,size } = req.query
      let current = page ? page : 1
      let pageSize = size ? size : 6
      //用户信息
      try{
       const [result,fields] = await pool.execute(`SELECT user.id,nickname,avatar FROM user 
       LEFT JOIN user_info ON user_info.userId=user.id   WHERE user.id != ${userId} LIMIT ${(current-1)*pageSize},${current*pageSize}`)  
        const list = SplicingImagePaths(result)  
        res.send({ code:200,msg:'请求成功',data:{ message:'查询成功',list } })
      }catch(error){
        console.log(`接口${req.path}发生错误,错误信息为${error}`)
        res.status(400).send({ msg:'请求失败',code:400,data:{ message:'查询失败' } })    
      } 
}

/**查询用户与角色权限 */
export const getUserRoleList = async(req,res)=>{
      const { page,size } = req.query
      if(!page || !size) return res.status(400).send({ msg:'请求失败',code:400,data:{ message:'参数错误' } })
      let current = page ? page : 1
      let pageSize = size ? size : 6
      try{
        const [result,fields] = await pool.execute(`SELECT user_info.userId AS id,nickname,avatar,roleId,field AS role FROM user_info 
          LEFT JOIN  user_role  ON user_info.userId = user_role.userId 
          LEFT JOIN role ON user_role.roleId = role.id  LIMIT ${(current-1)*pageSize},${current*pageSize}`)
          const [countResult,countFields] = await pool.execute(`SELECT COUNT(*) AS total FROM user `)
          let total = countResult[0] ? countResult[0].total :0
          const list = SplicingImagePaths(result)
          res.send({ code:200,msg:'请求成功',data:{ message:'查询成功',list,total } })
      }catch(error){
          console.log(`接口${req.path}发生错误,错误信息为${error}`)
          res.status(500).send({ msg:'查询失败',code:500,data:{ message:'查询失败' } })   
      }
}

/**封禁用户 */
export const increaseUserBan = async(req,res)=>{
    const { id } = req.body
    try{
      await pool.execute(`UPDATE user SET disabled=1 WHERE id=${id}`)
      res.send({ code:200,msg:'请求成功',data:{ message:'封禁成功' } })
    }catch(error){
      console.log(`接口${req.path}发生错误,错误信息为${error}`)
      res.status(500).send({ msg:'请求失败',code:500,data:{ message:'封禁失败' } })
    }
}

/**解禁用户 */
export const releaseUserBan = async(req,res)=>{
  const { id } = req.body
  try{
    await pool.execute(`UPDATE user SET disabled=0 WHERE id=${id}`)
    res.send({ code:200,msg:'请求成功',data:{ message:'解禁成功' } })
  }catch(error){
    console.log(`接口${req.path}发生错误,错误信息为${error}`)
    res.status(500).send({ msg:'请求失败',code:500,data:{ message:'解禁失败' } })
  }
}